﻿using System;
using System.Windows;
using Communications.PropertySearch;
using Microsoft.Phone.Controls;
using WP7Contrib.Communications;

namespace Communications
{
    using System.Diagnostics;
    using System.Reactive.Linq;
    using WP7Contrib.Logging;

    public partial class MainPage : PhoneApplicationPage
    {
        private readonly ISearchForProperties propertyService;
        private readonly IConfiguration _appConfig;
        private readonly ILog log;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            _appConfig = new AppConfig();

            log = new DebugLog();
            var resourceClient = new ResourceClient(log);
            propertyService = new PropertySearchServices(resourceClient, _appConfig);
        }

        private void GetRequestClick(object sender, RoutedEventArgs e)
        {
            var propertyCriteria = new PropertyCriteria {PlaceName = "london"};

            try
            {
                var sw = new Stopwatch();
                sw.Start();
                log.Write("Property search started...");
                propertyService.Search(1, 1000, propertyCriteria)
                    .ObserveOnDispatcher()
                    .Subscribe(result =>
                    {
                        log.Write("Properties found...");
                        log.Write("Property page size = {0}", result.PageSize);
                        log.Write("Property page index = {0}", result.PageIndex);

                        resultsCount.Text = string.Format("Property count = {0}", result.Items.Count);
                        response.Text = "Successfully returned propeerties...";
                    },
                    exception =>
                    {
                        response.Text = "Failed to get properties...";
                    },
                    () =>
                    {
                        sw.Stop();
                        log.Write("Elapsed time = {0} ms", sw.ElapsedMilliseconds);
                        log.Write("Searching for properties completed...");
                        elapsedTime.Text = string.Format("Elapsed time = {0} ms", sw.ElapsedMilliseconds);
                    });
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
    }
}